package cn.org.timespace.ons.util.ds;

import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.org.timespace.ons.util.ResourceContext;

/**
 * <p>
 * Easyframe框架提供连接工具类
 * </p>
 */

public class DataSourceUtil {
	
	private static final Log log = LogFactory.getLog(DataSourceUtil.class);
	
	private static DataSourceUtil tsDataSourceUtil = null;
	
	private static final String DATASOURCE_TYPE = "datasource.type";
	private static final String JDBC_URL = "jdbc.url";
	private static final String JDBC_DRIVER = "jdbc.driver";
	private static final String JDBC_USERNAME = "jdbc.username";
	private static final String JDBC_PASSWORD = "jdbc.password";
	
	private static final String DATASOURCE_TYPE_JDBC = "jdbc";
	private static final String DATASOURCE_TYPE_DBCP = "dbcp";
	
	private String datasourcetype;
	private String url;
	private String driver;
	private String username;
	private String password;
	
	private DataSourceUtil() {
		init();
	}

	public static DataSourceUtil getInstance() {
		if (tsDataSourceUtil == null) {
			tsDataSourceUtil = new DataSourceUtil();
		}
		return tsDataSourceUtil;
	}


	public Connection getConnection() {
		Connection connection = null;
		
		if(datasourcetype == null) datasourcetype = DATASOURCE_TYPE_JDBC;
		
		if(log.isInfoEnabled()) log.info("当前获取连接的类型是："+datasourcetype);
		
		if(datasourcetype.equals(DATASOURCE_TYPE_JDBC))
		{
			connection = getJDBCConnection();
		}
		else if(datasourcetype.equals(DATASOURCE_TYPE_DBCP))
		{
			
		}
		
		return connection;
	}


	private Connection getJDBCConnection() {
		Connection connection = null;
		
		try {
			Class.forName(driver);
			connection = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			
			if(log.isErrorEnabled()) log.info("获取Jdbc连接出错，原因是："+e.getMessage());
			e.printStackTrace();
			
			connection = null;
		}
		
		if(log.isErrorEnabled()) log.info("获取Jdbc连接成功！");
		
		return connection;
	}
	
	private void init(){
		datasourcetype = ResourceContext.getInstance().getParamValue(DATASOURCE_TYPE);
		url = ResourceContext.getInstance().getParamValue(JDBC_URL);
		driver = ResourceContext.getInstance().getParamValue(JDBC_DRIVER);
		username = ResourceContext.getInstance().getParamValue(JDBC_USERNAME);
		password = ResourceContext.getInstance().getParamValue(JDBC_PASSWORD);
	}
	
}
